/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

package gui.settings;

import gui.MainFrame;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

import web.Download;
import web.Retriever;

public class ProgressBar extends JPanel
                             implements ActionListener, 
                                        PropertyChangeListener {

    private static final long serialVersionUID = 1L;
    
	private JProgressBar progressBar;
    private JButton startButton;
    private JTextArea taskOutput;
    private static JFrame frame;
    private Task task;
    
    static private MainFrame mainframe;

    class Task extends SwingWorker<Void, Void> {
        /*
         * Main task. Executed in background thread.
         */
        @Override
        public Void doInBackground() {
            
        	mainframe.resetTextArea();
        	mainframe.empty2ndChart();
    		
    		try{
    			String url  = "";
    			String query;
    			
    			
    			for(int i= ConfigFile.getInstance().getTERM_NUM(); i>0; i--)
    			{
    				url = "";
        			query = "filetype:pdf";
    				
    				for(int a=0 ; a<i ; a++)
    				{
    					query = mainframe.termList1st.get(a).getTerm() + " " + query;
    				}
    				
    				if(url.equals("")) {
    					
    					List<String> results = new Retriever().retrieve(query);
    					if(results.size() != 0){
    						
    						int c = 0;
    						
    						while(url.equals("") && (c < results.size())) {
	    						
    							url = results.get(c);			
	    						
	    						long size = Download.getFileSize(url);
	    						
	    						if(size > 1000000 || size < 10000) { 
	    							url = "";
	    						} else {
	    							taskOutput.append("Number of results " + results.size() + "\n");
		    						taskOutput.append("Result number  " + c + " url: " + url + "\n");
	    							taskOutput.append("Query: " + query + "\n");
	    							i=0;
	    						}
	    						
	    						c++;
	    						
    						}
    						
    					}
    				}
    			}
    					
    			taskOutput.append("Starting download\nFile size: " + Download.getFileSize(url) + " byte\n");
    			taskOutput.append("Downloading... \n");
    			String fileName = Download.download(url,"c:"+File.separator);	
    			taskOutput.append("Download completed \n");
    			
    			mainframe.path2nd = fileName;
    			mainframe.extension2nd = fileName.substring(fileName.lastIndexOf('.'));
    			mainframe.updateIndex();
    			mainframe.updateChart();
    			
    		} catch(Exception e) {  
    			
    		}
    		return null;
        }
            
        /*
         * Executed in event dispatching thread
         */
        @Override
        public void done() {
            Toolkit.getDefaultToolkit().beep();
            startButton.setEnabled(true);
            setCursor(null); //turn off the wait cursor
            taskOutput.append("Done!\n");
            try{
            	Thread.sleep(1000L);
            	frame.setVisible(false);
            	frame.dispose();
	        } catch(Exception e) {  
				
			}
            
        }
        
    }

    public ProgressBar() {
        super(new BorderLayout());

        //Create the demo's UI.
        startButton = new JButton("Start");
        startButton.setActionCommand("start");
        startButton.addActionListener(this);

        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(0);
        progressBar.setStringPainted(false);
        progressBar.setIndeterminate(true);

        taskOutput = new JTextArea(5, 20);
        taskOutput.setMargin(new Insets(5,5,5,5));
        taskOutput.setEditable(false);

        JPanel panel = new JPanel();
        panel.add(startButton);
        panel.add(progressBar);

        add(panel, BorderLayout.PAGE_START);
        add(new JScrollPane(taskOutput), BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    }

    /**
     * Invoked when the user presses the start button.
     */
    public void actionPerformed(ActionEvent evt) {
        startButton.setEnabled(false);
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        //Instances of javax.swing.SwingWorker are not reusuable, so
        //we create new instances as needed.
        task = new Task();
        task.addPropertyChangeListener(this);
        task.execute();
    }

    /**
     * Invoked when task's progress property changes.
     */
    public void propertyChange(PropertyChangeEvent evt) {
        if ("progress" == evt.getPropertyName()) {
            int progress = (Integer) evt.getNewValue();
            progressBar.setValue(progress);
            taskOutput.append(String.format(
                    "Completed %d%% of task.\n", task.getProgress()));
        } 
    }


    /**
     * Create the GUI and show it. As with all GUI code, this must run
     * on the event-dispatching thread.
     */
    public static void createAndShowGUI(MainFrame mframe) {
    	
    	mainframe=mframe;
    	
        //Create and set up the window.
        frame = new JFrame("Search & Download");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new ProgressBar();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);


        frame.setBounds( 	mainframe.getX()+(mainframe.getWidth()/2) ,
        					mainframe.getY()+(mainframe.getHeight()/2) ,
        					300,
        					300);
        
        frame.setLocation(	frame.getX() - (frame.getWidth()/2) ,
        		 			frame.getY() - (frame.getHeight()/2));
        
        frame.setVisible(true);
    }

}
